import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import UserHome from '@/views/UserHome.vue'
import UserDocuments from '@/views/UserDocuments.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/user',
    name: 'UserHome',
    component: UserHome,
    meta: {
      title: '个人中心',
      requiresAuth: true
    }
  },
  {
    path: '/documents',
    name: 'UserDocuments',
    component: UserDocuments,
    meta: {
      title: '我的文档',
      requiresAuth: true
    }
  },
  {
    path: '/community',
    name: 'Community',
    component: () => import('@/views/Community.vue'),
    meta: {
      title: '社区'
    }
  },
  {
    path: '/database',
    name: 'Database',
    component: () => import('@/views/Database.vue'),
    meta: {
      title: '资料库'
    }
  },
  {
    path: '/shop',
    name: 'Shop',
    component: () => import('@/views/Shop.vue'),
    meta: {
      title: '商城'
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 熊猫系统` : '熊猫系统'
  
  // 如果需要登录但未登录，重定向到登录页
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 如果已登录且访问登录页，重定向到首页
    if (to.path === '/login' && token) {
      next('/home')
    } else {
      next()
    }
  }
})

export default router